/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.LoanManager;

import gui.ItemManager.ItemManagerBase;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import resource.Macro;
import utilities.Codecs;
import utilities.DBConnector;
import utilities.EmailReminder;
import utilities.Helper;
import utilities.Prompt;

/**
 *
 * @author fangchengjia
 */
public class ReturnItem extends ItemManagerBase {
    String _call_no = "";
    String _type = "";
    String _name = "";
    String _author = "";
    String _publish_year = "";
    String _publisher = "";
    String _category = "";
    String _isbn = "";
    String _register_date = "";
    String _price = "NZ$";
    String _status = "On Loan";
    String _owner = "None";
    String _return_date = "";
    String _notes = "";
    String _id = "";
    
    DBConnector dbSession = getDBSession();
    javax.swing.JTable target_table;
    /**
     * Creates new form IM_Edit
     * @param dbSession
     * @param target_table
     * @param row_num
     */
    public ReturnItem(DBConnector dbSession, JTable target_table, int row_num) {
        super(dbSession);
        setTargetTable(target_table);
//        int row_num = target_table.getSelectedRow();
        row_num = target_table.convertRowIndexToModel(row_num);
        if (row_num != -1){
            _call_no = (String)target_table.getModel().getValueAt(row_num, 0);
            _type = (String)target_table.getModel().getValueAt(row_num, 1);
            _name = (String)target_table.getModel().getValueAt(row_num, 2);
            _author = (String)target_table.getModel().getValueAt(row_num, 3);
            _publish_year = (String)target_table.getModel().getValueAt(row_num, 4);
            _publisher = (String)target_table.getModel().getValueAt(row_num, 5);
            _category = (String)target_table.getModel().getValueAt(row_num, 6);
            _isbn = (String)target_table.getModel().getValueAt(row_num, 7);
            _register_date = (String)target_table.getModel().getValueAt(row_num, 8);
            _price = (String)target_table.getModel().getValueAt(row_num, 9);
            _status = Macro.ITEM_STATUS_ON_LOAN;
            _owner = (String)target_table.getModel().getValueAt(row_num, 11);
            _return_date = (String)target_table.getModel().getValueAt(row_num, 12);
            _notes = (String)target_table.getModel().getValueAt(row_num, 13);
            _id = (String)target_table.getModel().getValueAt(row_num, 14);

            if (!_category.equals("No Category")){
                String category_tmp = dbSession.load(Macro.DB_CATEGORY, 
                        String.format("Name='%s'",
                                Codecs.encode(_category)), "Name");
                _category = Codecs.decode(category_tmp);
            }
            if (!_owner.equals("None")){
                if (dbSession.check(Macro.DB_MEMBERSHIP, 
                        String.format("Name='%s'", Codecs.encode(_owner)))){
                    String owner_tmp = dbSession.load(Macro.DB_MEMBERSHIP, 
                            String.format("Name='%s'",
                                    Codecs.encode(_owner)), "Name");
                    _owner = Codecs.decode(owner_tmp);
                }
                else{
                    Prompt.warning(String.format("%s no longer exists", _owner));
                }
            }
        }
        else{
            Prompt.warning("No data selected");
        }
    }
    
    public boolean needToRemind(int days){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        try {
            Date date = format.parse(_return_date);
            Date time_to_remind = format.parse(Helper.getDaysFromToday(days));
            return date.before(time_to_remind);
        } catch (ParseException ex) {
            Logger.getLogger(ReturnItem.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }
    
    public void returnItem(){
        int n = JOptionPane.showConfirmDialog(this,
            String.format("Do you want to return item %s?", _name),
            "Confirm Return",
            JOptionPane.YES_NO_OPTION);
        if (n == 0){
            String values[] = {_call_no, _type, _name, _author, _publish_year, 
                _publisher, _category, _isbn, _register_date, _price,
                Macro.ITEM_STATUS_ON_SHELF, Macro.ITEM_OWNER_NONE, "", _notes};
            if (dbSession.check(Macro.DB_ITEM,
                    String.format("id='%s'", Codecs.encode(_id)))){
                dbSession.update(Macro.DB_ITEM,
                        Helper.encodeValues(TABLE_MODEL, values),
                    String.format("id='%s'", Codecs.encode(_id)));
                searchLoanedItems();
            }
            else{
                Prompt.warning("The record does not exist.");
            }
        }
    }
    
    public void sendReminder(String src_email, String password){
        int n = JOptionPane.showConfirmDialog(this,
            String.format("Do you want to send reminder for: %s?", _name),
            "Confirm Send",
            JOptionPane.YES_NO_OPTION);
        if (n == 0){
            if (dbSession.check(Macro.DB_ITEM,
                    String.format("id='%s'", Codecs.encode(_id)))){
                if (dbSession.check(Macro.DB_MEMBERSHIP,
                        String.format("Name='%s'", Codecs.encode(_owner)))){
                    String email = Helper.searchOwnerAttributeByName(
                            dbSession, Macro.DB_MEMBERSHIP,
                            Codecs.encode(_owner),
                            Macro.MEMBERSHIP_EMAIL_L);
                    EmailReminder.sendreminder(src_email, password, email,
                            Macro.EMAIL_REMINDER_HEARDER,
                            String.format(Macro.EMAIL_REMINDER_CONTENT, _name,
                                    _return_date));
                }
                else{
                    Prompt.warning("The owner does not exist.");
                }
            }
            else{
                Prompt.warning("The record does not exist.");
            }
        }
    }
}
